package org.ymf.task.once;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.ymf.dao.PostEsDao;
import org.ymf.entity.Post;
import org.ymf.entity.PostEs;
import org.ymf.service.PostService;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 帖子 => 全量同步到 Elasticsearch
 * </p>
 *
 * @author Malphite
 * @since 2023-08-01
 */
@Slf4j
// todo 取消注释开启任务
// @Component
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class FullSyncPostToEs {

    @Resource
    private PostService postService;

    @Resource
    private PostEsDao postEsDao;

    @Test
    public void run() {
        List<Post> list = postService.list();
        if (list.isEmpty()) return;
        List<PostEs> esList = list.stream().map(Post :: transform).collect(Collectors.toList());
        final int pageSize = 500;
        int total = esList.size();
        log.info("FullSyncPostToEs start, total {}", total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, total);
            log.info("sync from {} to {}", i, end);
            postEsDao.saveAll(esList.subList(i, end));
        }
        log.info("FullSyncPostToEs end, total {}", total);
    }

}
